package com.chenlipeng.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.chenlipeng.utils.CookieStroeUtil;
import com.chenlipeng.utils.HttpClientUtils;
import com.chenlipeng.utils.ImagePreProcess;
import com.chenlipeng.utils.NhkyLogin;
import com.chenlipeng.utils.RedisUtil;

import net.sf.json.JSONObject;

/**
 * 
 * @author ChenLiPeng
 * @date   2017年10月1日
 */
@Controller
@RequestMapping(value = "/user")
public class LoginController {

	@RequestMapping("/login")
	@ResponseBody
	public Map<String, Object>  login(HttpServletRequest request, HttpServletResponse response, @RequestParam(required=false) String username,
			@RequestParam(required=false) String password) {

		Map<String, Object> map = NhkyLogin.getBaseValue(); 
		Map<String, Object> resultScore=new HashMap<String, Object>();
		if (map.containsKey("exception")) { 
			System.out.println(map.get("exception"));
			resultScore.put("exception", map.get("exception"));
			String score=RedisUtil.getJedis().get(username);
			JSONObject json = JSONObject.fromObject(score);
			resultScore.put("userScore", json);
		}else{
			resultScore=NhkyLogin.isLogin(map);
			String checkcodeUrl = HttpClientUtils.BASE_URL + map.get("urlcode") + "/VerifyCode.aspx";
			Map<String, Object> pars = ImagePreProcess.downloadImage(checkcodeUrl, username + ".png");
			map.put("Cookie", (CookieStroeUtil) pars.get("Cookie"));
			map.put("checkCode", (String) pars.get("checkCode"));
			map.put("username", username);
			map.put("password", password);
			
			JSONObject jsonObject = JSONObject.fromObject(resultScore);
			RedisUtil.getJedis().set(username, jsonObject.toString());
		}
		return resultScore;
	}
}
